import saleplanApi from "../../../common/api/breedsales/planbills.api.js"
import { auditStateToHtml } from "../../../common/json-mapping/state-content-mapping.js";
import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import watermark from '../../../common/watermark.js';
import { Collaboration_APP, TEST_NUMBER, YY_NUMBER } from '../../../../../public/js/config/config.js';

(function (window, document, $) {
    $('body').attr('data-weui-theme', 'light'); //强制光明模式

    new Vue({
        el: '#vehicle-app',
        data() {
            const statusMap = {
                '1': { label: '已保存', class: "success" },
                '2': { label: '已提交', class: "primary" },
                '3': { label: '已审核', class: "dark" },
                '22': { label: '未结算完', class: "warning" },
                '21': { label: '已结算完', class: "success" },
                '99': { label: '已删除', class: "danger" },
            }
            return {
                typeMap: {
                    'submit': '提交',
                    'unsubmit': '反提交',
                    'audit': '审核',
                    'unaudit': '反审核',
                    'delete': '删除'
                },
                navList: [
                    { text: '全部', value: 0 },
                    { text: '已保存', value: 1 },
                    { text: '已提交', value: 2 },
                    { text: '已审核', value: 3 },
                ],
                activeNavValue: 0,
                showPopoverItem: {},
                queryKey: '',
                showReloadTip: false,
                showDialog: false,
                pageInfo: {
                    pageIndex: 0,
                    pageSize: 10
                },
                isEnd: true,
                salePlanList: [],
                timer: null,
                submitId: '',
                tags: '',
                pigTypeOptions: [],
                operatItem: {},
                operationType: ''
            }
        },
        async created() {
            $(`#vehicle-app`).removeClass('d-none')
            this.queryDate = moment().format('YYYY-MM-DD')
            let url = location.href
            let params = {} // url参数
            for (let key of (new URL(url)).searchParams.entries()) {
                key[1] ? params[key[0]] = key[1] : ''
            }
            this.getPigTypeOption()
            this.getList()
        },
        mounted() {
            // this._initSlide()
            this.pullLoad()
            this.watermarkBgImg()
            document.addEventListener('scroll', (e) => {
                this.showPopoverItem = {}
            })
            document.addEventListener('click', (e) => {
                let pop = $(`#operation-popover`)
                if (!pop.is(e.target) && pop.has(e.target).length === 0) {
                    this.showPopoverItem = {}
                }
            })
        },
        methods: {
            // 获取销售品类数组字典
            getPigTypeOption() {
                requestDict(DictionaryType.LEVEL_TYPE).then(res => {
                    this.pigTypeOptions = res.data
                })
            },
            // 根据数据字典值获取名臣
            getNameById(id, options) {
                let obj = options.find(item => item.value == id)
                if (obj) {
                    return obj.displayName
                }
                return id
            },
            // 点击选项栏
            clickNav(item) {
                this.activeNavValue = item.value
                this.reloadList()
            },
            // 搜索列表
            search() {
                this.reloadList()
            },
            // 刷新列表
            reloadList() {
                this.isEnd = true
                this.pageInfo.pageIndex = 0
                this.getList()
            },
            // 获取列表
            getList: async function () {
                if (this.loading) return
                let date = moment(this.queryDate).format('YYYY-MM-DD');

                let personOrgs = await saleplanApi.postUserOrgsList();
                let _personOrg = [];
                personOrgs.forEach(item => {
                    if (item.optTag == 1 && item.tags.indexOf('210') !== -1) {
                        _personOrg.push(item.oId);
                    }
                });

                let query = {
                    ...this.pageInfo,
                    billStatus: this.activeNavValue ? this.activeNavValue : '',
                    searchInfo: this.queryKey,
                    fitlerOrgs: _personOrg
                }
                this.loading = true
                saleplanApi.getSalePlanList(query).then(res => {
                    let data = res.items.map(item => {
                        item.billStatusHtml = auditStateToHtml(item.billStatus)
                        item.bizDateStr = moment(item.bizDate).format('YYYY-MM-DD')
                        item.entryDateStr = moment(item.entryDate).format('YYYY-MM-DD')
                        return item
                    })
                    this.loading = false
                    if (this.pageInfo.pageIndex === 0) {
                        this.salePlanList = data
                    } else {
                        this.salePlanList = this.salePlanList.concat(data)
                    }
                    let totalCount = res.totalCount
                    this.isEnd = this.salePlanList.length >= totalCount
                })
                    .catch(() => {
                        this.loading = false
                    });
            },
            // 清空搜索框
            clearSearch() {
                this.queryKey = ''
                this.reloadList()
            },
            //TODO : 上拉加载
            pullLoad() {
                let that = this
                // 监听滚动的父容器
                $(document.body).infinite(10).on("infinite", () => {
                    if (this.timer) return
                    this.timer = setTimeout(() => {
                        this.timer = null
                    }, 500);
                    if (!this.isEnd) {
                        this.pageInfo.pageIndex = this.pageInfo.pageIndex + 1
                        this.getList()
                    }
                });
            },
            // 返回主页
            returnHome() {
                location.href = '../../main.html'
            },
            // 点击列表操作图标
            clickItemOpera(item) {
                $('.weui-mask.weui-mask--visible').css('opacity', '1')

                this.showPopoverItem = item
            },
            editPlan(item) {
                location.href = `../saleplans/writesaleplans.html?id=${item.id}`
            },
            doOperation(type, item) {
                let that = this
                if (type === 'audit') {
                    $.modal({
                        autoClose: false,
                        title: `核定数量 - 提示`,
                        text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					    <div style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
                            <div class="weui-cell" style="padding: 15px;">
                            <div class="weui-cell__hd"><label>核定数量(头)</label></div>
                            <div class="weui-cell__bd">
                              <input class="weui-input clearContent masterpad" type="text" placeholder="请输入核定数量..."
                                  id="checkCount" value="${that.showPopoverItem.count}" style="border-bottom:1px solid #bababa">
                            </div></div> </div>`,
                        buttons: [
                            {
                                text: "取消", className: "default", onClick: function () {
                                    $(this).hide();
                                    $('.weui-mask.weui-mask--visible').css('opacity', '0')
                                    $('.weui-mask.weui-mask--visible').css('visibility', 'hidden')
                                }
                            },
                            {
                                text: "确定", onClick: function () {
                                    let checkCountVal = $('#checkCount').val()
                                    if (!Utils.IsNotNull(checkCountVal)) {
                                        return $.toptip(`请输入核定数量!`, 'warning');
                                    }
                                    if (!(/(^[1-9]\d*$)/.test(checkCountVal))) {
                                        $.toptip(`核定数量必须为大于0的整数!`, 'warning');
                                        return false; // 立即停止遍历并返回false
                                    }
                                    $(this).hide();
                                    that.showPopoverItem = {}
                                    that.showDialog = true
                                    that.operatItem = item
                                    that.operationType = type
                                }
                            }
                        ]
                    });
                }
                else {
                    $('.weui-mask.weui-mask--visible:first').css('visibility', 'visible')
                    this.showPopoverItem = {}
                    this.showDialog = true
                    this.operatItem = item
                    this.operationType = type
                }

            },
            viewDetail(item) {
                location.href = `../saleplans/saleplansdetail.html?id=${item.id}`
            },
            operationCancel() {
                this.showDialog = false
                $('.weui-mask.weui-mask--visible').css('opacity', '0')
                $('.weui-mask.weui-mask--visible').css('visibility', 'hidden')
            },
            operationConfirm() {
                this.showDialog = false
                let type = this.operationType
                let item = this.operatItem
                let promise = null
                if (type === 'submit') {
                    promise = saleplanApi.submitSalePlan(item.id)
                } else if (type === 'unsubmit') {
                    promise = saleplanApi.unsubmitSalePlan(item.id)
                } else if (type === 'audit') {
                    promise = saleplanApi.auditSalePlan(item.id, $('#checkCount').val())
                } else if (type === 'unaudit') {
                    promise = saleplanApi.unauditSalePlan(item.id)
                } else if (type === 'delete') {
                    promise = saleplanApi.deleteSalePlan(item.id)
                }
                promise.then(res => {
                    $.toptip(`${this.typeMap[type]}成功`, 'success');
                    this.reloadList()
                    $('.weui-mask.weui-mask--visible').css('opacity', '0')
                    $('.weui-mask.weui-mask--visible').css('visibility', 'hidden')

                }, err => {
                    // $('.weui-mask.weui-mask--visible').css('opacity', '0')
                    // $('.weui-mask.weui-mask--visible').css('visibility', 'hidden')
                })
            },
            addplan() {
                location.href = './writesaleplans.html'
            },
            //水印信息
            watermarkBgImg() {
                let _userInfo = JSON.parse(Utils.GetSessionStorage("SNAccountEply")) || {};
                watermark.set(_userInfo.name + _userInfo.numCode);// 水印
                //saleplanApi.queryUserName(Utils.GetQueryString('state') || YY_NUMBER.sourceID).then(res => {
                //    watermark.set(_userInfo.un + res.code);// 水印
                //}).catch(_ => {
                //    watermark.set(_userInfo.un);// 水印
                //});
            }

        }
    });

})(window, document, jQuery)